package com.aaa.book_mall.util;

import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 短信工具类
 * @ClassName: MsgUtils
 * @Author: fengyun
 * @Date: 2021/2/21 19:34
 * @Version: 1.0
 */
public class MsgUtils {
    public static int sendMsg(String phonenumber,HttpServletRequest request){
        String host = "https://dxyzm.market.alicloudapi.com";
        String path = "/chuangxin/dxjk";
        String method = "POST";
        String appcode = "58d8c95b67fd40cc977cbb427471ffa4";//开通服务后 买家中心-查看AppCode
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
//        生成随机验证码
        int random =(int) (Math.random()*9000)+1000;
//       将验证码添加到session中
        request.getSession().setAttribute("authcode",random);

        querys.put("content", "【创信】你的验证码是："+random+"，3分钟内有效！");
        querys.put("mobile", phonenumber);
        Map<String, String> bodys = new HashMap<String, String>();

        int i = 0;
        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
           if(response!=null){
               System.out.println(response.toString());
               i=1;//1:短信发送成功，0：短信发送失败
               return i;
           }
            //获取response的body
            //System.out.println(EntityUtils.toString(response.getEntity()));
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            return i;
        }
    }
}
